<template>
  <div class="app-container">
    <el-form
      class="box-container"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="进修科目类型" prop="registerDeptType" v-if="false">
        <el-select
          v-model="queryParams.registerDeptType"
          placeholder="请选择招生类型"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerDeptTypeList"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="进修科目名称" prop="registerDeptName">
        <el-input
          v-model="queryParams.registerDeptName"
          placeholder="请输入进修科目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <div class="box-container">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['business:registerDept:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['business:registerDept:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['business:registerDept:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['business:registerDept:export']"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
    </div>

    <div class="box-container">
      <el-table
        v-loading="loading"
        @sort-change="handleSortChange"
        :data="registerDeptList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column
          label="进修科目类型"
          align="center"
          prop="registerDeptTypeName"
          v-if="false"
        />
        <el-table-column
          label="进修科目名称"
          align="center"
          prop="registerDeptName"
        />
        <el-table-column
          label="进修科目编号"
          align="center"
          sortable="custom"
          prop="registerDeptNumber"
        />
        <el-table-column
          label="学员端排序"
          align="center"
          sortable="custom"
          prop="registerStudentNumber"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.editing">
              <el-input
                v-model="tempData[scope.row.id]"
                size="mini"
                @keyup.enter.native="saveEdit(scope.row)"
              ></el-input>
              <el-button
                type="text"
                size="mini"
                icon="el-icon-check"
                @click="saveEdit(scope.row)"
              ></el-button>
              <el-button
                type="text"
                size="mini"
                icon="el-icon-close"
                @click="cancelEdit(scope.row)"
              ></el-button>
            </div>
            <span v-else>
              {{ scope.row.registerStudentNumber }}
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="startEdit(scope.row)"
              ></el-button>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="科室负责人"
          align="center"
          prop="manageNickName"
        />
        <el-table-column
          label="带教秘书"
          align="center"
          prop="secretaryNickName"
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['business:registerDept:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['business:registerDept:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改进修科目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="进修科目类型" prop="registerDeptType" v-if="false">
          <el-select
            v-model="form.registerDeptType"
            placeholder="请选择招生类型"
            filterable
            clearable
          >
            <el-option
              v-for="(item, index) in registerDeptTypeList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="进修科目名称" prop="registerDeptName">
          <el-input
            v-model="form.registerDeptName"
            placeholder="请输入进修科目名称"
          />
        </el-form-item>
        <el-form-item label="进修科目编号" prop="registerDeptNumber">
          <el-input
            v-model="form.registerDeptNumber"
            placeholder="请输入进修科目编号"
          />
        </el-form-item>
        <el-form-item label="学员端排序" prop="registerStudentNumber">
          <el-input
            v-model="form.registerStudentNumber"
            type="number"
            placeholder="请输入排序编号"
          />
        </el-form-item>
        <el-form-item label="科室负责人" prop="manageUserId">
          <el-select
            v-model="form.manageUserId"
            placeholder="请选择科室负责人"
            filterable
            clearable
          >
            <el-option
              v-for="(item, index) in ksList"
              :key="index"
              :label="item.userName + '：' + item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="带教秘书" prop="secretaryUserId">
          <el-select
            v-model="form.secretaryUserId"
            placeholder="请选择带教秘书"
            filterable
            clearable
          >
            <el-option
              v-for="(item, index) in sysUserList"
              :key="index"
              :label="item.userName + '：' + item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { consts } from "@/api/business/consts";
import {
  addRegisterDept,
  delRegisterDept,
  getMaxDeptNumber,
  getRegisterDept,
  listRegisterDept,
  updateRegisterDept,
} from "@/api/business/registerDept";
import { listAllByRole } from "@/api/system/user";
export default {
  name: "RegisterDept",
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 进修科目表格数据
      registerDeptList: [],
      tempData: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        registerDeptType: null,
        registerDeptName: null,
        registerDeptNumber: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{ required: true, message: "主键不能为空", trigger: "blur" }],
        registerDeptType: [
          { required: true, message: "进修科类型不能为空", trigger: "blur" },
        ],
        registerDeptName: [
          { required: true, message: "进修科目名称不能为空", trigger: "blur" },
        ],
        registerStudentNumber: [
          { required: true, message: "学员端排序不能为空", trigger: "blur" },
        ],
        registerDeptNumber: [
          { required: true, message: "进修科目编号不能为空", trigger: "blur" },
        ],
        manageUserId: [
          { required: true, message: "科室负责人不能为空", trigger: "blur" },
        ],
        secretaryUserId: [
          { required: true, message: "带教秘书不能为空", trigger: "blur" },
        ],
      },
      registerDeptTypeList: consts.registerDeptTypeList,
      sysUserList: [],
      ksList: [],
    };
  },
  created() {
    this.getList();
    this.listAllUser();
  },
  methods: {
    getMaxDeptNumber() {
      getMaxDeptNumber().then((response) => {
        this.form.registerDeptNumber = Number(response.data) + 1;
      });
    },
    listAllUser() {
      // listAllUser().then(response => {
      //   this.sysUserList = response.data
      // })
      listAllByRole(3).then((response) => {
        this.sysUserList = response.data;
      });
      listAllByRole(6).then((response) => {
        this.ksList = response.data;
      });
    },
    /** 查询进修科目列表 */
    getList() {
      this.loading = true;
      listRegisterDept(this.queryParams).then((response) => {
        this.registerDeptList = response.rows.map((item) => ({
          ...item,
          editing: false, //初始化编辑状态
        }));
        console.log(this.registerDeptList);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        registerDeptType: null,
        registerDeptName: null,
        registerDeptNumber: null,
        registerStudentNumber: null,
        manageUserId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSortChange(column) {
      if (column.order) {
        // 根据 prop 设置排序字段
        if (column.prop === "registerStudentNumber") {
          this.queryParams.sortColumnName = "register_student_number";
        } else if (column.prop === "registerDeptNumber") {
          this.queryParams.sortColumnName = "register_dept_number";
        }
        // 设置排序方向
        this.queryParams.sortOrderClass =
          column.order === "ascending" ? "asc" : "desc";
      } else {
        // 取消排序 (点击了第三次)
        this.queryParams.sortColumnName = null;
        this.queryParams.sortOrderClass = null;
      }
      this.getList(); // 重新获取数据
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMaxDeptNumber();
      this.open = true;
      this.title = "添加进修科目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRegisterDept(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改进修科目";
      });
    },
    startEdit(row) {
      this.$set(row, "editing", true);
      console.log(row.registerStudentNumber);
      this.$set(this.tempData, row.id, row.registerStudentNumber);
    },
    async saveEdit(row) {
      const updatedRow = {
        ...row,
        registerStudentNumber: this.tempData[row.id],
      };
      try {
        await updateRegisterDept({
          id: row.id,
          registerStudentNumber: this.tempData[row.id],
        });
        Object.assign(row, updatedRow);
        this.$set(row, "editing", false);
        this.$message.success("排序成功");

        // 模拟点击“学员端排序”列的表头进行排序
        this.handleSortChange({
          prop: "registerStudentNumber",
          order: "ascending",
        }); // 假设默认升序
      } catch (error) {
        console.error("更新失败:", error);
        this.$message.error("更新失败");
      }
    },
    cancelEdit(row) {
      this.$set(row, "editing", false);
      this.$delete(this.tempData, row.id);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateRegisterDept(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegisterDept(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除进修科目编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRegisterDept(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/registerDept/export",
        {
          ...this.queryParams,
        },
        `registerDept_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
